<template>
  <div
    class="tablevxe"
    v-if="chartsConData.ways !== '' && chartsConData.type !== ''"
  >
    <vxe-table
      v-if="tableShow"
      ref="vxeTable"
      border
      width="100%"
      height="400"
      column-min-width="100px"
      :auto-resize="true"
      resizable
      align="center"
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
      :sort-config="{ showIcon: false }"
      @edit-closed="editClosedEvent"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column
        v-for="(item, index) in tableLabel"
        :key="index"
        :field="item.name"
        :title="item.title"
        sortable
        :edit-render="{ name: 'input', attrs: { type: 'text' } }"
      >
        <template
          v-if="
            chartsConData.ways !== '2' &&
              chartsConData.type1 !== 'z2' &&
              chartsConData.ways !== '2' &&
              chartsConData.type1 !== 'z3' &&
              chartsConData.ways !== '5' &&
              chartsConData.type1 !== 'z2' &&
              chartsConData.ways !== '5' &&
              chartsConData.type1 !== 'z3'
          "
          v-slot:header="{ column }"
        >
          <span>{{ column.title }}</span>
          <span class="custom-sort is-order">
            <i
              style="cursor:pointer;"
              :class="[
                order[index]
                  ? order[index] === 1
                    ? 'el-icon-bottom'
                    : 'el-icon-top'
                  : 'el-icon-d-caret'
              ]"
              @click="handleOrder(item.name, index)"
            /> </span></template
      ></vxe-table-column>
      <vxe-table-column width="40" style="cursor:pointer">
        <template v-slot="{ row }"
          ><i class="el-icon-delete" @click="removeEvent(row)"></i
        ></template>
      </vxe-table-column>
    </vxe-table>
    <div class="addRow">
      <el-button type="primary" @click="handleAdd">最后一行增加</el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'tablevxe',
  data() {
    return {
      tableData: [],
      tableLabel: {},
      tableShow: true
    }
  },
  methods: {
    // 点击表头处理升序降序
    handleOrder(data, index) {
      this.tableData.sort(this.compare(data, index))
      let ord = this.order[index] ? (this.order[index] == 1 ? 2 : 1) : 1
      this.setOrder({ key: 'order', value: ord, index: index })
      this.setDrawFlag()
    },
    // 比较大小
    compare(propertyName, index) {
      if (this.order[index] === 1) {
        return function(ob1, ob2) {
          let value1 = ob1[propertyName]
          let value2 = ob2[propertyName]
          if (value2 > value1) {
            return 1
          } else if (value2 < value1) {
            return -1
          } else {
            return 0
          }
        }
      } else {
        return function(ob1, ob2) {
          let value1 = ob1[propertyName]
          let value2 = ob2[propertyName]
          if (value2 > value1) {
            return -1
          } else if (value2 < value1) {
            return 1
          } else {
            return 0
          }
        }
      }
    },
    // 删除
    removeEvent(row) {
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$refs.vxeTable.remove(row)
          let index = this.tableData.findIndex(item => item._XID === row._XID)
          this.tableData.splice(index, 1)
          this.editClosedEvent()
        }
      })
    },
    // 点击最后一行增加
    handleAdd() {
      this.insertEvent(-1)
    },
    async insertEvent(row) {
      let record = {}
      let { row: newRow } = await this.$refs.vxeTable.insertAt(record, row)
      await this.$refs.vxeTable.setActiveCell(newRow, 'sex')
      let insertRecords = this.$refs.vxeTable.getInsertRecords()
      insertRecords.forEach(item => {
        for (let key in item) {
          if (key === '时间') {
            item[key] = item['_XID']
          } else {
            item[key] = key !== '_XID' ? '' : item[key]
          }
        }
        this.tableData.push(item)
      })

      this.editClosedEvent()
    },
    converNumber() {
      this.chartData.forEach(item => {
        if (item.hasOwnProperty('value')) {
          item['value'] = Number(item.value)
        }
        if (item.hasOwnProperty('percent')) {
          item['percent'] = Number(item.percent)
        }
        if (item.hasOwnProperty('媒体来源')) {
          item['媒体来源'] = Number(item['媒体来源'])
        }
      })
    },
    setData() {
      let obj = { dateArr: [], dataMap: {} }
      this.tableData.forEach(item => {
        obj.dateArr.push(item['时间'])
        for (let key in item) {
          if (key !== '时间') {
            item[key] = Number(item[key])
            if (obj.dataMap.hasOwnProperty(key)) {
              obj.dataMap[key].push(item[key])
            } else {
              obj.dataMap[key] = []
              obj.dataMap[key].push(item[key])
            }
          }
        }
      })
      return obj
    },
    editClosedEvent() {
      let list = []
      let obj = {}
      this.converNumber()
      switch (this.chartsConData.ways) {
        case '2':
        case '5':
          switch (this.chartsConData.type1) {
            case 'z2':
              obj = this.setData()
              for (let i in obj.dataMap) {
                if (i !== '_XID') {
                  let item = obj.dataMap[i]
                  list.push({
                    name: i
                  })
                  for (let j in obj.dateArr) {
                    let date = obj.dateArr[j]
                    list[list.length - 1][date] = item[j]
                  }
                }
              }
              this.setChartsData1({ data: list })
              break
            case 'z3':
            case 'l1':
              obj = this.setData()
              for (let i in obj.dataMap) {
                if (i !== '_XID') {
                  let item = obj.dataMap[i]
                  for (let j in obj.dateArr) {
                    list.push({
                      name: i,
                      year: obj.dateArr[j],
                      value: item[j]
                    })
                  }
                }
              }
              this.setChartsData1({ data: list })
              break
          }
          break
      }

      this.setDrawFlag()
    },
    ...mapMutations('charts', ['setDrawFlag', 'setChartsData1']),
    ...mapMutations('chartsCon', ['setOrder', 'setState'])
  },
  computed: {
    ...mapState('charts', ['chartData', 'chartsConData']),
    ...mapState('chartsCon', ['order'])
  },
  watch: {
    chartData(data) {
      this.tableShow = false
      let _this = this
      this.tableLabel = []
      this.tableData = data
      let list = JSON.parse(JSON.stringify(data))
      switch (this.chartsConData.type) {
        case '1': // 饼图
          switch (this.chartsConData.ways) {
            case '1': // 媒体来源
              this.tableLabel = [
                { name: 'label', title: '媒体类型' },
                { name: 'value', title: '数据量' },
                { name: 'percent', title: '百分比' }
              ]
              break
            case '5': // 情感
              this.tableLabel = [
                { name: 'label', title: '属性' },
                { name: 'value', title: '数据量' },
                { name: 'percent', title: '百分比' }
              ]
              break
          }
          break
        case '2':
        case '3':
          switch (this.chartsConData.ways) {
            case '1':
              switch (this.chartsConData.type1) {
                case 'z1':
                case 'z4':
                case 'l2':
                  this.tableLabel = [
                    { name: 'label', title: '媒体类型' },
                    { name: 'value', title: '数据量' }
                  ]
                  break
                case 'z3':
                  this.tableLabel = [
                    { name: 'name', title: '媒体类型' },
                    { name: 'value', title: '数据量' }
                  ]
                  break
                default:
                  this.tableLabel = [
                    { name: 'name', title: '媒体类型' },
                    { name: '媒体来源', title: '数据量' }
                  ]
                  break
              }
              break
            case '2':
            case '5':
              let obj = {}
              switch (this.chartsConData.type1) {
                case 'z1':
                case 'z4':
                case 'l2':
                  this.tableLabel = [
                    { name: 'label', title: '时间' },
                    { name: 'value', title: '数据量' }
                  ]
                  break
                case 'z2':
                  this.tableLabel = [{ name: '时间', title: '时间' }]
                  this.tableData = []
                  obj = { dateArr: [], dataMap: {} }
                  list.forEach(el => {
                    if (obj.dateArr.length === 0) {
                      for (let i in el) {
                        if (i !== 'name') {
                          obj.dateArr.push(i)
                        }
                      }
                    }
                    _this.tableLabel.push({ name: el.name, title: el.name })
                    obj.dataMap[el.name] = []
                    for (let i in el) {
                      if (i !== 'name') {
                        obj.dataMap[el.name].push(el[i])
                      }
                    }
                  })
                  list.forEach(item => {
                    obj.dateArr.forEach((item1, index) => {
                      if (item.year === item1) {
                        obj.dataMap[item.name][index] = item.value
                      }
                    })
                  })
                  obj.dateArr.forEach((item, index) => {
                    _this.tableData.push({})
                    _this.tableData[_this.tableData.length - 1]['时间'] = item
                    for (let key in obj.dataMap) {
                      _this.tableData[_this.tableData.length - 1][key] =
                        obj.dataMap[key][index]
                    }
                  })
                  break
                default:
                  this.tableLabel = [{ name: '时间', title: '时间' }]
                  this.tableData = []
                  obj = { dateArr: [], dataMap: {} }
                  list.forEach(el => {
                    if (!obj.dateArr.includes(el.year)) {
                      obj.dateArr.push(el.year)
                    }
                    if (!obj.dataMap.hasOwnProperty(el.name)) {
                      obj.dataMap[el.name] = []
                      _this.tableLabel.push({ name: el.name, title: el.name })
                    }
                  })
                  list.forEach(item => {
                    obj.dateArr.forEach((item1, index) => {
                      if (item.year === item1) {
                        obj.dataMap[item.name][index] = item.value
                      }
                    })
                  })
                  obj.dateArr.forEach((item, index) => {
                    _this.tableData.push({})
                    _this.tableData[_this.tableData.length - 1]['时间'] = item
                    for (let key in obj.dataMap) {
                      _this.tableData[_this.tableData.length - 1][key] =
                        obj.dataMap[key][index]
                    }
                  })
                  this.$refs.vxeTable.updateData()
              }
              break
          }
          break
        case '5':
          this.tableLabel = [
            { name: 'name', title: '关键词' },
            { name: 'value', title: '数值' }
          ]
          break
        case '4':
          this.tableLabel = [
            { name: 'name', title: '地域' },
            { name: 'value', title: '数值' }
          ]
          break
      }
      this.$nextTick(() => {
        _this.tableShow = true
      })
    },
    'chartsConData.ways'(val) {
      this.setState([{ key: 'order', value: [] }])
    },
    'chartsConData.type1'(val) {
      this.setState([{ key: 'order', value: [] }])
    }
  }
}
</script>

<style scoped>
.tablevxe {
  height: 400px;
}
.addRow {
  float: right;
  margin-top: 10px;
}
</style>
